package com.jielihaofeng.atguigu.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 * @author Johnnie Wind
 * @description NIO 客户端
 * @date 2021/11/25 16:01
 */
public class NIOClient {
    public static void main(String[] args) throws IOException {
        // 得到一个 SocketChannel 通道
        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.configureBlocking(false);
        InetSocketAddress inetSocketAddress = new InetSocketAddress("localhost", 6666);

        if (!socketChannel.connect(inetSocketAddress)) {
            while (!socketChannel.finishConnect()) {
                System.out.println("因为客户端连接需要时间，客户端不会阻塞，可以做其他工作...");
            }
        }

        // 如果连接就发数据
        String str = "Hello, 借力好风";
        // 包裹一个字节数组到ByteBuffer
        ByteBuffer buffer = ByteBuffer.wrap(str.getBytes());
        // 发送数据
        socketChannel.write(buffer);
        // 代码停在这
        System.in.read();
    }
}
